<script setup lang="ts">
import { useRoute, useRouter } from 'vue-router'
import { computed, ref } from 'vue'
import { storage } from '../../stores/mystore/auth'
import { Notify, showNotify, Toast } from 'vant'
import request from '@/utils/request'

const isFocused = ref(false) // 控制高亮状态

function getStock(stock: number | string) {
  if (typeof stock === 'number') {
    if (stock > 99) {
      return '充足'
    }
    if (stock > 0 && stock <= 99) {
      return '紧张'
    }
    if (stock === 0) {
      return '稀少'
    }
  }
  // if (typeof stock === 'string') {
  //   return stock.includes('充足')
  // }
}

const route = useRoute()
const router = useRouter()

const c_good = reactive({
  authority: '',
  create_tm: '',
  desc: '',
  discount: 0.00,
  id: '',
  img_url: '',
  name: '',
  pay: '',
  price: '',
  racking: '',
  stock: '',
  stock_num: 0,
  tag_desc1: '',
  tag_desc2: '',
  tag_desc3: '',
  type: '',
  update_tm: '2025-06-21T00:22:06.000+00:00',

  copy_good_link: '', // 黏贴的商品链接
})

// 购买弹窗信息
const buyDialogInfo = reactive({
  // id: '', // 订单ID
  order_good_id: '', // 商品ID
  order_name: '', // 订单名称
  order_desc: '', // 订单描述
  order_price: '', // 订单 单价
  order_sum: 0, // 订单总价
  order_total: 0, // 订单下单个数
  order_img_url: '', // 订单商品图片链接
  order_type: 0, // 订单处理类型 0待处理/1处理中/2处理完成

  order_buy_id: '', // 购买人ID
  order_buy_user: '', // 购买人
  order_buy_user_tel: '', // 购买人电话

  order_other_info: '', // 订单附加信息
  order_buy_command: '', // 订单口令

  // order_create_tm: '', // 订单创建时间
  // order_operate_tm: '', // 订单处理时间
})

const userdata = reactive({
  across_num: '',
  avatarBase64: '',
  avatar_url: '',
  create_tm: '',
  email: '',
  encrypt_pwd: '',
  encryption_algorithm: '',
  freeze_ornnt: '',
  id: '',
  role_num: '',
  tel_num: '',
  update_tm: '',
  username: '',
  wechat_abt: '',
  account_money: 0, // 余额
  b_account: 0.0000, // 余额（保留四位小数）
})

// 购买弹窗相关
const showBuy = ref(false) // 创建订单弹窗
const buyCount = ref(0) // 订单购买数量
const buyCommand = ref('') // 订单口令
// 计算购买总价
const totalPrice = computed(
  () => {
    console.log(typeof buyCount.value)
    console.log(Number(buyCount.value))
    buyCount.value = Number(buyCount.value)
    if (!c_good.price || isNaN(Number(buyCount.value))) {
      showNotify({ type: 'warning', message: '请输入数值' })
      buyCount.value = 0 // 重置购买数量
      return '0.00'
    }
    else {
      return (c_good.price ? (Number(c_good.price) * buyCount.value).toFixed(2) : '0.00')
    }
  },
)

function formateBuyCount() {

}

// 打开购买弹窗
function openBuy() {
  // if (c_good.copy_good_link === '') {
  //   showNotify({ type: 'warning', message: '请填写商品链接信息', duration: 500 })
  //   return
  // }
  const userInfo = storage.get('userInfo', 'local')
  console.log('USERINFO', userInfo)
  if (!userInfo) {
    showNotify({ type: 'warning', message: '登录后购买' })
    return
  }
  showBuy.value = true
}

// 购买商品
function onBuyConfirm() {
  // 判断购买数量
  if (buyCount.value <= 0) {
    showNotify({ type: 'warning', message: '购买数量至少 1', duration: 500 })
    return
  }

  if (c_good.copy_good_link === '') {
    showNotify({ type: 'warning', message: '请填写商品链接信息', duration: 500 })
    return
  }

  // 组装订单信息
  buyDialogInfo.order_good_id = c_good.id // 订单商品ID
  buyDialogInfo.order_name = c_good.name // 订单名称
  buyDialogInfo.order_desc = c_good.desc // 订单描述
  buyDialogInfo.order_price = c_good.price, // 订单 单价
  buyDialogInfo.order_sum = Number(totalPrice.value), // 订单总价
  buyDialogInfo.order_total = buyCount.value // 订单下单个数
  buyDialogInfo.order_img_url = c_good.img_url // 订单商品图片链接
  buyDialogInfo.order_type = 0 // 订单处理类型 0待处理/1处理中/2处理完成

  buyDialogInfo.order_buy_id = userdata.id // 购买人唯一ID
  buyDialogInfo.order_buy_user = userdata.username // 购买人
  buyDialogInfo.order_buy_user_tel = userdata.tel_num // 购买人电话

  buyDialogInfo.order_other_info = c_good.copy_good_link // 订单附加信息
  buyDialogInfo.order_buy_command = buyCommand.value // 订单口令

  console.log('购买订单信息', buyDialogInfo)

  createOrder(buyDialogInfo)
}

// 查询列表
async function createOrder(orderParam: any) {
  try {
    const res = await request.post('/dragon/orderCreate', { ...orderParam })
    console.log(res)

    if (res.code == 200 && res.msg === '订单创建失败' && res.data === '账户已冻结') {
      showNotify({ type: 'danger', message: '账户已冻结，请联系管理员', duration: 1000 })
      return
    }
    if (res.code == 200 && res.msg === '订单创建失败' && res.data === '余额不足') {
      showNotify({ type: 'warning', message: '账户余额不足，请充值', duration: 1000 })
      return
    }
    if (res.code == 200 && res.msg === '订单创建成功' && res.data === `${userdata.username}下单成功`) {
      showNotify({ type: 'success', message: '下单成功，请关注订单状态', duration: 5000 })

      // 关闭购买弹窗
      showBuy.value = false

      // 重置购买数量和口令 totalPrice 需支付  是计算属性 不用重置
      buyCount.value = 0
      buyCommand.value = ''

      // 查询并更新 浏览器存储的用户信息
      const userInfo = storage.get('userInfo', 'local')
      console.log('更新前的用户信息 local', userInfo)

      const res = await request.post('/dragon/getuserInfo', {
        uName: userdata.username,
        uCellphone: userdata.tel_num,
      })
      console.log('查询到的用户信息', res.data)

      storage.set('userInfo', res.data, {
        type: 'local',
        expires: 1, // 一天过期
        encrypt: false, // 是否加密
      })

      const userInfo1 = storage.get('userInfo', 'local')
      console.log('更新 local 后的用户信息', userInfo1)

      router.replace('/order')
    }
  }
  catch (error) {

  }
  finally {
    console.log()
  }
}

const isLogin = computed(() => !!storage.get('userInfo', 'local'))
onMounted(() => {
  // console.log("商品详情 ",route.query)
  Object.assign(c_good, route.query)
  c_good.stock_num = Number(c_good.stock || 0)

  // console.log("c_good",c_good)
  const userInfo = storage.get('userInfo', 'local')
  // console.log("USERINFO",userInfo)

  if (userInfo) {
    // @ts-ignore
    // userdata.across_num = userInfo.across_num
    // @ts-ignore
    userdata.avatarBase64 = userInfo.avatarBase64
    // @ts-ignore
    userdata.avatar_url = userInfo.avatar_url
    // @ts-ignore
    userdata.create_tm = userInfo.create_tm
    // @ts-ignore
    // userdata.email = userInfo.email
    // @ts-ignore
    // userdata.encrypt_pwd = userInfo.encrypt_pwd
    // @ts-ignore
    // userdata.encryption_algorithm = userInfo.encryption_algorithm
    // @ts-ignore
    // userdata.freeze_ornnt = userInfo.freeze_ornnt
    // @ts-ignore
    userdata.id = userInfo.id
    // @ts-ignore
    userdata.role_num = userInfo.role_num
    // @ts-ignore
    userdata.tel_num = userInfo.tel_num
    // @ts-ignore
    userdata.update_tm = userInfo.update_tm
    // @ts-ignore
    userdata.username = userInfo.username
    // @ts-ignore
    userdata.wechat_abt = userInfo.wechat_abt
    // @ts-ignore
    userdata.account_money = userInfo.account_money
    // @ts-ignore
    userdata.b_account = userInfo.b_account
  }

  // console.log("userdata",userdata)
})

// 返回首页
function goHome() {
  router.replace({ name: 'home' })
}

function goLogin() {
  router.replace({ name: 'profile' })
}
</script>

<template>
  <div class="detail-bg">
    <div class="detail-img-box">
      <img :src="c_good.img_url" class="detail-img">
    </div>
    <div class="detail-card">
      <div class="detail-title">
        {{ c_good.name }}
      </div>
      <div class="detail-row">
        <span class="detail-label">价格</span>
        <span class="detail-price">{{ c_good.price }}</span>
        <span class="detail-unit">元</span>

        <!-- 库存充足 -->
        <span v-if="getStock(c_good.stock_num) === '充足'" class="detail-stock1">
          库存充足
        </span>
        <span v-else-if="getStock(c_good.stock_num) === '紧张'" class="detail-stock2">
          库存紧张
        </span>
        <span v-else="getStock(c_good.stock_num) === '稀少'" class="detail-stock3">
          暂无库存
        </span>
      </div>
    </div>
    <!-- <div class="detail-section-title">商品详情</div>
    <div class="detail-link-tip">
      <span style="color:#f44336;font-weight:bold;">请粘贴商品链接！例如：</span><br>
      <span style="color:#1976d2;word-break:break-all;">
        【X鱼】https://XX.XX.XX/h.TK7UoNX?tk=FuPPe605Jze MF278
        【我在X鱼发布了「使命召唤手游代练·暴风碾压！」】点击链接直接打开
      </span>
    </div> -->

    <!-- <van-cell-group style="margin-top: 10px;border-radius: 25px">
      <van-field
        style="overflow-y: auto; max-height: 300px;border-radius: 25px; /* 按需调整高度 */"
        type="textarea"
        show-word-limit
        v-model="c_good.copy_good_link"
        placeholder="请输入内容"
        :class="{ 'highlight-border': isFocused }"
        @focus="isFocused = true"
        @blur="isFocused = false"
        class="rounded-input"
        autosize
         maxlength="9999"
      />
    </van-cell-group> -->
    <!-- 底部操作栏 -->
    <div class="detail-footer">
      <button v-if="isLogin" class="footer-btn home" @click="goHome">
        首页
      </button>
      <button v-if="!isLogin" class="footer-btn home" @click="goLogin">
        去登录
      </button>
      <button class="footer-btn buy" @click="openBuy">
        购买
      </button>
    </div>

    <!-- 购买弹窗 -->
    <van-action-sheet v-model:show="showBuy" title="创建订单" closeable>
      <div class="buy-sheet">
        <div class="buy-row">
          <!-- <span style="font-size: 16px">购买数量</span> -->

          <div class="buy-stepper">
            <button @click="buyCount > 0 && (buyCount--)">
              -
            </button>
            <!-- <span style="width: 200px">{{ buyCount }}</span> -->
            <van-field
              v-model="buyCount"
              label="购买数量"
              placeholder="请输入购买数量"
              @blur="formateBuyCount"
            />
            <button @click="buyCount++">
              +
            </button>
          </div>
        </div>

        <div class="buy-row">
          <!-- <span style="font-size: 25px">购买口令</span> -->
          <!-- <input
            class="buy-input"
            v-model="buyCommand"
            placeholder="请输入购买口令"
            /> -->
          <!-- <van-field v-model="buyCommand" label="购买口令" placeholder="请输入购买口令" /> -->
        </div>
        <div class="detail-link-tip">
          <span style="color:#f44336;font-weight:bold;">请粘贴商品链接！例如：</span><br>
          <span style="color:#1976d2;word-break:break-all;">
            【X鱼】https://XX.XX.XX/h.TK7UoNX?tk=FuPPe605Jze MF278
            【我在X鱼发布了「使命召唤手游代练·暴风碾压！」】点击链接直接打开
          </span>
        </div>

        <van-cell-group style="margin-top: 10px;border-radius: 25px">
          <van-field
            v-model="c_good.copy_good_link"
            style="overflow-y: auto; max-height: 300px;border-radius: 25px; /* 按需调整高度 */"
            type="textarea"
            show-word-limit
            placeholder="请输入内容"
            :class="{ 'highlight-border': isFocused }"
            class="rounded-input"
            autosize
            maxlength="9999"
            @focus="isFocused = true"
            @blur="isFocused = false"
          />
        </van-cell-group>

        <div class="buy-bottom">
          <span class="buy-total">
            需支付：
            <span style="color:#ff5722;">
              {{ totalPrice }}元
            </span>
          </span>
          <span class="buy-balance">
            账户余额：
            <span style="color:#1976d2;">
              {{ userdata.b_account.toFixed(4) || 0.00 }}元
            </span>
          </span>
        </div>

        <!-- <button
          class="buy-confirm"
          @click="onBuyConfirm"
          style="display: inline-flex; align-items: center;"
        >
          <span style="margin-right: 8px">
            <van-loading type="spinner" color="#1989fa" size="16px" />
          </span>
          <span>购买</span>
        </button> -->
        <VanButton

          type="primary"
          round block
          size="normal"
          icon="http://118.178.124.108:9000/budys/btn_buy.png"
          style="margin: 0 auto; width: 95%;  font-size: 30px;
          font-weight: bold;
          background: linear-gradient(90deg, #1976d2, #6a8dff); color: #fff; border-radius: 22px; margin-bottom: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center;"
          @click="onBuyConfirm"
        >
          购买
        </VanButton>
      </div>
    </van-action-sheet>
  </div>
</template>

<style scoped>
.van-field__control {
  height: 120px !important; /* 覆盖默认高度 */
  padding: 12px; /* 内边距 */
  margin-bottom: 20px; /* 下外边距 */
}
/* 基础圆角样式 */
.rounded-input :deep(.van-field__control) {
  border-radius: 12px; /* 圆角大小 */
  border: 1px solid #ccc; /* 默认边框 */
  padding: 15px;
  transition: border-color 0.3s; /* 平滑过渡效果 */
}

/* 聚焦时高亮边框 */
.highlight-border :deep(.van-field__control) {
  border-color: #1989fa; /* Vant 主题蓝色 */
  box-shadow: 0 0 0 2px rgba(25, 137, 250, 0.2); /* 发光效果 */
}
.van-field__textarea {
  overflow-y: auto !important;
  resize: none !important; /* 禁止用户拖拽调整大小 */
}
.goods-tag {
  font-size: 12px;
  padding: 2px 4px;
  border-radius: 6px;
  font-weight: 500;
  display: inline-block;
}
.goods-tag.quality {
  background: #e844cf80;
  color: #fff;
}
.detail-bg {
  background: #f7f7fa;
  min-height: 100vh;
  padding-bottom: 80px;
}
.detail-img-box {
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f7f7fa;
  padding: 32px 0 12px 0;
}
.detail-img {
  width: auto;
  height: 335px;
  object-fit: contain;
  border-radius: 18px;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.detail-card {
  background: #fff;
  border-radius: 12px;
  margin: 0 16px 16px 16px;
  padding: 18px 18px 12px 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.detail-row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}
.detail-label {
  color: #222;
  margin-right: 8px;
}
.detail-price {
  color: #ff5722;
  font-size: 24px;
  margin-right: 2px;
}
.detail-unit {
  color: #222;
  font-size: 16px;
  margin-right: 16px;
}
.detail-stock1 {
  color: #16c96b;
  background: #eafff3;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 14px;
  margin-left: auto;
}
.detail-stock2 {
  color: #fbde00fb;
  background: #eafff3;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 14px;
  margin-left: auto;
}
.detail-stock3 {
  color: #979898;
  background: #eafff3;
  border-radius: 4px;
  padding: 2px 8px;
  font-size: 14px;
  margin-left: auto;
}
.detail-title {
  font-size: 20px;
  font-weight: 600;
  margin-top: 8px;
  color: #222;
}
.detail-section-title {
  text-align: center;
  font-size: 18px;
  color: #888;
  margin: 10px 0 5px 0;
  font-weight: bold;
}
.detail-link-tip {
  background: #fff;
  border-radius: 10px;
  margin: 0 0px;
  padding: 6px 6px;
  font-size: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}
.detail-footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  z-index: 100;
  background: transparent;
  justify-content: space-around;
  padding: 0 0 12px 0;
}
.footer-btn {
  flex: 1;
  margin: 0 8px;
  height: 48px;
  border: none;
  border-radius: 24px;
  font-size: 18px;
  font-weight: bold;
  color: #fff;
  cursor: pointer;
}
.footer-btn.home {
  background: linear-gradient(90deg, #6a8dff, #ff7e5f);
}
.footer-btn.buy {
  background: linear-gradient(90deg, #ff7e5f, #ff3c3c);
}
.buy-sheet {
  padding: 12px 0 0 0;
}
.buy-row {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 18px;
  margin: 18px 0 18px 0;
  padding: 0 16px;
}
.buy-stepper {
  height: 45px;
  font-weight: 600;
  display: flex;
  align-items: center;
  margin-left: 16px;
  background: #f7f7fa;
  border-radius: 8px;
  overflow: hidden;
}
.buy-stepper button {
  width: 32px;
  height: 32px;
  border: none;
  background: #eaeaea;
  font-size: 20px;
  color: #333;
  cursor: pointer;
}
.buy-stepper span {
  width: 36px;
  text-align: center;
  font-size: 18px;
  background: #fff;
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
}
.buy-input {
  margin-left: 16px;
  flex: 1;
  border: none;
  border-radius: 6px;
  background: #f7f7fa;
  padding: 8px 12px;
  font-size: 16px;
  outline: none;
}
.buy-bottom {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 24px 0 12px 0;
  padding: 0 16px;
}
.buy-total {
  color: #ff5722;
  font-size: 14px;
  font-weight: bold;
}
.buy-balance {
  color: #1976d2;
  font-size: 14px;
}
.buy-confirm {
  width: 90%;
  margin: 0 5%;
  height: 44px;
  background: linear-gradient(90deg, #1976d2, #6a8dff);
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  border: none;
  border-radius: 22px;
  margin-bottom: 18px;
  cursor: pointer;
}
</style>

<route lang="json5">
{
  name: 'goods-detail',
  path: '/goods/:id',
  meta: { title: '商品详情' }
}
</route>
